package com.msh.starter.common.instance;

import com.msh.frame.client.interfaces.IClassLoadLog;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;

/**
 * @author shihu
 */
public class ApplicationContextUtil implements ApplicationContextAware, IClassLoadLog {

  private static ApplicationContext applicationContext = null;

  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    if (ApplicationContextUtil.applicationContext == null) {
      ApplicationContextUtil.applicationContext = applicationContext;
    }
  }

  @Override
  public String logInfo() {
    return new StringBuilder()
        .append("----执行类 ")
        .append(ApplicationContextUtil.class)
        .append("\r\n")
        .append("--------加载类 ")
        .append(ApplicationContextUtil.class)
        .append("\r\n")
        .toString();
  }

  public static void publishEvent(Object object) {
    if (applicationContext == null) {
      return;
    }
    applicationContext.publishEvent(object);
  }

  public static void publishEvent(ApplicationEvent event) {
    if (applicationContext == null) {
      return;
    }
    applicationContext.publishEvent(event);
  }

  public static Object getBean(String name) {
    if (applicationContext == null) {
      return null;
    }
    return applicationContext.getBean(name);
  }

  public static <T> T getBean(Class<T> clazz) {
    if (applicationContext == null) {
      return null;
    }
    return applicationContext.getBean(clazz);
  }

  public static <T> T getBean(String name, Class<T> clazz) {
    if (applicationContext == null) {
      return null;
    }
    return applicationContext.getBean(name, clazz);
  }
}
